package cn.yuxiaoyuan.template;

import cn.hutool.http.HttpUtil;
import cn.yuxiaoyuan.domain.DistanceResult;
import cn.yuxiaoyuan.exception.GlobalException;
import cn.yuxiaoyuan.properties.MapProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author solargen
 * @version 1.0
 * @date 2025/6/28 11:27
 */
public class MapTemplate {

    private MapProperties properties;

    public MapTemplate(MapProperties mapProperties) {
        this.properties = mapProperties;
    }

    /**
     *  得到的是后端计算的预计结果
     * @param mode  驾车模式 driving、walking、bicycling
     * @param fromLat
     * @param fromLng
     * @param toLat
     * @param toLng
     * @return
     */
    public DistanceResult distanceMeasure(String mode, double fromLat ,
                                                 double fromLng , double toLat , double toLng ){
        try {
            //拼接测距请求
            String url = String.format(properties.getDistanceUrl(),
                    mode,fromLat, fromLng, toLat, toLng, properties.getKey());
            //发送测距请求
            String json = HttpUtil.get(url);
            JSONObject jsonObject = JSON.parseObject(json);
            //判断结果
            if(!jsonObject.get("status").toString().equals("0")){
                throw new GlobalException(jsonObject.get("message").toString());
            }
            //拿到结果
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray rows = result.getJSONArray("rows");
            if(rows.size() == 0)throw new GlobalException("没有测距结果");
            JSONArray elements = rows.getJSONObject(0).getJSONArray("elements");
            if(elements.size() == 0)throw new GlobalException("没有测距结果");
            JSONObject distanceResult = elements.getJSONObject(0);
            DistanceResult finalResult = new DistanceResult();
            //距离换算成千米
            finalResult.setDistanceKm(Float.valueOf(distanceResult.get("distance").toString())/1000);
            //时长换算成分钟
            finalResult.setDurationMin(Integer.valueOf(distanceResult.get("duration").toString()) /60);
            return finalResult;
        }  catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
    }
}
